package com.cheyun.netsalev3.widget

import android.app.Dialog
import android.os.Bundle
import android.text.Html
import android.view.*
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.databinding.MyContentDialogLayoutBinding
import kotlin.reflect.KFunction1

class MyContentDialog : DialogFragment() {
    lateinit var binding: MyContentDialogLayoutBinding
    /**系统调用这个来获得对话片段的布局，不管是否显示为对话框或嵌入片段。*/
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        //将布局膨胀为对话框或嵌入片段
        binding = DataBindingUtil.inflate(inflater, R.layout.my_content_dialog_layout, container, false)
        initView()
        binding.setLifecycleOwner(this)
        return binding.root
    }


    private fun initView() {
        binding.cancelButton.setOnClickListener {
            dismiss()
        }
        binding.okButton.setOnClickListener {
            dismiss()
            onClickOk?.apply {
                this()
            }
        }
        if(html){
            binding.conetenTex.text = Html.fromHtml(content)
        }else{
            binding.conetenTex.text = content
        }
        binding.titleText.text = title

        callbackInitView?.apply {
            this(binding)
        }
    }


    /**系统仅在对话框中创建布局时调用此操作。*/
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        val window = dialog.window
        window.setBackgroundDrawableResource(android.R.color.transparent)
        return dialog
    }

    var title = ""
    var content = ""
    var html = false
    var onClickOk: (() -> Unit)? = null
    var callbackInitView: KFunction1<@ParameterName(name = "binding") MyContentDialogLayoutBinding, Unit>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            title = it.getString("title")
            content = it.getString("content")
            html = it.getBoolean("html")
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(title: String, content: String,html:Boolean = false) =
                MyContentDialog().apply {
                    arguments = Bundle().apply {
                        putString("title", title)
                        putString("content", content)
                        putBoolean("html", html)
                    }
                }
    }


}